package com.example.autopia.model.Repositories

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.autopia.model.Item.HotNews
import com.example.autopia.utilities.KEY_BD_HOT_NEWS
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class HotNewsRepository {
    private val database = FirebaseDatabase.getInstance()
    private var reference = database.getReference(KEY_BD_HOT_NEWS)

    fun addHotNews(photo: String, text: String): Boolean {
        var status = false
        val newItem = reference.push()
        val hotNews = HotNews(newItem.key?: "", "", "test")
        newItem.setValue(hotNews)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun deleteHotNews(hotNewsId: String): Boolean {
        var status = false
        reference.child(hotNewsId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }
    fun getAllItems() : MutableLiveData<ArrayList<HotNews>>{
        val itemsList = ArrayList<HotNews>()
        val result = MutableLiveData<ArrayList<HotNews>>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children) {
                    val id = itemSnapshot.child("id").value.toString()
                    val photo = itemSnapshot.child("photo").value.toString()
                    val title = itemSnapshot.child("title").value.toString()
                    val hotNews = HotNews( id, photo,title)
                    itemsList.add(hotNews)
                }
                Log.d("Yatoro","В списке горячих новостей "+ itemsList.size.toString())
                result.value = itemsList
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в HotNews")
            }
        })
        return result
    }
}